package org.kev.transit;

import java.util.HashMap;

import org.kev.transit.util.TestDataHelper;
import org.kev.transit.util.TransitConst;
import org.kev.transit.util.TransitUtil;
import org.kev.transit.worker.DataWorker;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

/**
 * Screen allows application settings to be changed
 * Today, only allows main URL and transit system to be changed.  Someday it will pull this data
 * from a web service call and cache the result in the local DB.  This screen also allows the user to
 * clear all cached data so the app will pull new data from the internet. 
 * @author kevin
 * 
 */
public class SettingsActivity extends DataActivity{
	static final private int ABOUT_ID = Menu.FIRST;
	static final private int UPDATE_ID = Menu.FIRST + 1;
	
	public static final String TAG = "SettingsActivity";
	private EditText mUrl = null;
	private EditText mSystem = null;
	
	protected final Handler mHandler = new Handler();
	protected final Handler mProgressHandler = new Handler();
	protected static ProgressDialog mPogressD = null;
	protected static boolean isUpdate= false;
	private int progress=0;
	private static final DataWorker mWorker = new DataWorker();
	public SettingsActivity() {
		
	}

	/** Called with the activity is first created. */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);	
		Log.d(TAG, "onCreate");

		 requestWindowFeature(Window.FEATURE_PROGRESS);
		// Inflate our UI from its XML layout description.
		setContentView(R.layout.settings);

//		Intent intent=getIntent();
//		String type=intent.getType();
		mUrl = (EditText) findViewById(R.id.url);
		mSystem = (EditText) findViewById(R.id.system);

		// Hook up button presses to the appropriate event handler.
		//((Button) findViewById(R.id.back)).setOnClickListener(mBackListener);
		((Button) findViewById(R.id.update)).setOnClickListener(mUpdateListener);
	}

	/**
	 * Called when the activity is about to start interacting with the user.
	 */
	@Override
	protected void onResume() {
		super.onResume();
		Log.d(TAG, "onResume Save Prefs!");
		/*if(!isUpdate){
	        getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
	                Window.PROGRESS_VISIBILITY_ON);
		}*/
		SharedPreferences settings = getSharedPreferences(
				TransitConst.PREFS_NAME, 0);
		TransitConf.url=settings.getString(TransitConst.URL_PREF, "none");
		TransitConf.system=settings.getString(TransitConst.SYSTEM_PREF, "none");
	}

	/**
	 * 
	 * I am being paused save all prefs
	 */
	@Override
	protected void onPause() {
		super.onPause();
		Log.d(TAG, "onPAUSE Save Prefs!");
		save();
	}


	/**
	 * Called when your activity's options menu needs to be created.
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		// We are going to create two menus. Note that we assign them
		// unique integer IDs, labels from our string resources, and
		// given them shortcuts.
		menu.add(0, ABOUT_ID, R.string.about_menu).setShortcut('0', 'a');
		menu.add(0, UPDATE_ID, R.string.update).setShortcut('1','u');

		return true;
	}

	/**
	 * Called right before your activity's option menu is displayed.
	 */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);

		// Before showing the menu, we need to decide whether the clear
		// item is enabled depending on whether there is text to clear.
		// menu.setItemShown(CLEAR_ID, mEditor.getText().length() > 0);

		return true;
	}

	/**
	 * Called when a menu item is selected.
	 */
	@Override
	public boolean onOptionsItemSelected(Menu.Item item) {
		switch (item.getId()) {
		case DataActivity.ABOUT_ID:
			aboutScreen();
			return true;
		case UPDATE_ID:
			save();
			updateData();
			return true;
		}

		return super.onOptionsItemSelected(item);
	}

	/**
	 * save settings
	 */
	private void save() {
		TransitConf.system=mSystem.getText().toString();
		TransitConf.url=mUrl.getText().toString();
		Log.d(TAG, TransitConf.toXML());
		HashMap <String,String> values = new HashMap <String,String>(2);
		values.put("TransitConst.SYSTEM_PREF",TransitConf.system);
		values.put(TransitConst.URL_PREF, TransitConf.url);
		TransitUtil.savePref(this, values);
		/*
		SharedPreferences settings = getSharedPreferences(TransitConst.PREFS_NAME, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString(TransitConst.SYSTEM_PREF, TransitConf.system);
		editor.putString(TransitConst.URL_PREF, TransitConf.url);
		editor.commit();
		*/
		

	}

	/**
	 * Update app data from the internet start a worker thead (UpdateWoker) that
	 * does all of the work in the background may want to display a progress
	 * dialog here somday if this takes a long time right now it assumes that it
	 * all work can happen before any of the others screens need the data
	 */
	private void updateData() {
      //  getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
      //          Window.PROGRESS_VISIBILITY_ON);
        setProgressBarVisibility(true);
        setProgressBarIndeterminate(true);
        Log.d(TAG,"handler"+mHandler+"runnable"+mUpdateResults);
	   
		mWorker.init(this, mHandler, mUpdateResults);
		Thread t = new Thread(mWorker);
		t.start();
	}
    // Create runnable for posting
    final Runnable mUpdateResults = new Runnable() {
        
        public void run() {
        	Log.d(TAG,"mUpdateResults.run() ");
        	
        	//getWindow().setFeatureInt(Window.FEATURE_PROGRESS,Window.PROGRESS_VISIBILITY_OFF);
        	setProgressBarVisibility(false);
        	isUpdate=true; //data is up to date
        	
        	Log.d(TAG,"dissmiss p dialog() ");

        }
    };
    final Runnable mPrgressResults = new Runnable() {
        
        public void run() {
        	Log.d(TAG,"mPrgressResults.run() ");
    		progress+=1000;
    		if(progress>9997)
    			progress=0;
    		Log.d(TAG,"set progress="+progress);
    		getWindow().setFeatureInt(Window.FEATURE_PROGRESS,progress);
    		
        }
    };
	/**
	 * A call-back for when the user presses the back button.
	 */

	OnClickListener mBackListener = new OnClickListener() {
		public void onClick(View v) {

			finish();
		}
	};
	/**
	 * A call-back for when the user presses the back button.
	 */
	OnClickListener mUpdateListener = new OnClickListener() {
		public void onClick(View v) {
			save();
			updateData();
		}
	};


	@Override
	public void setData() {

		TestDataHelper helper = new TestDataHelper(this,mHandler, mPrgressResults);
		helper.getTestContent();
		
	}

	public void nextScreen() {
		//does nothing here
		
	}


}
